package com.boomsecret.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by wangjinliang on 2018/1/23.
 */
public class SemaphoreDemo {

    private static final int PERSON_COUNT = 8;
    private static final int THREAD_POOL_COUNT = 5;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_COUNT);
        for (int index = 0; index < PERSON_COUNT; index ++) {
            executorService.execute(()->{
                BankOperation.saveMoney();
            });
        }
        executorService.shutdown();
    }
}

class BankOperation {
    private static Semaphore semaphore = null;

    static {
        semaphore = new Semaphore(2, true);
    }

    public static void saveMoney() {
        try {
            semaphore.acquire();
            System.out.println("开始服务, threadId:" + Thread.currentThread().getId());
            Thread.sleep(2000);
            System.out.println("结束服务, threadId:" + Thread.currentThread().getId());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}